package org.wangle.starter.lock.annotation.aop;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.wangle.starter.lock.annotation.RedisLock;
import org.wangle.starter.lock.redis.RLock;

import java.lang.reflect.Method;


@Slf4j
@Aspect
public class RedisLockAspect {

    @Around("@annotation(org.wangle.starter.lock.annotation.RedisLock)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取被拦截的类名和方法名
        log.info("class=" + joinPoint.getSignature().getDeclaringTypeName() +
                "and method name=" + joinPoint.getSignature().getName());
        //获取被拦截的类名和方法名
        log.info("class=" + joinPoint.getSignature().getDeclaringTypeName() +
                "and method name=" + joinPoint.getSignature().getName());
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        RedisLock annotation = method.getAnnotation(RedisLock.class);
        String key = annotation.key();
        Object[] args = joinPoint.getArgs();
        String keyValue = args[0].toString();
        String requestId = args[1].toString();
        if(ObjectUtils.isEmpty(args)){
            throw new RuntimeException("分布式锁需要key值和当前请求表示标示");
        }
        try {
            RLock.tryLock(key+":"+keyValue, requestId);
           return joinPoint.proceed(args);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            RLock.unLock(key+":"+keyValue, requestId);
        }
        return joinPoint.proceed(args);

    }


}
